package cn.itcast.handler;

import cn.itcast.pojo.Menu;
import cn.itcast.pojo.Role;
import cn.itcast.service.MenuService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;


@Component
public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    AntPathMatcher pathMatcher = new AntPathMatcher();

    @Reference
    private MenuService menuService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取当前请求地址
        String requestUrl = ((FilterInvocation)object).getRequestUrl();
        //查询数据库中所有的路径
        List<Menu> menus = menuService.getMenus();
        for (Menu menu : menus) {
            if(pathMatcher.match(menu.getLinkUrl(),requestUrl)){
                Set<Role> roles =  menu.getRoles();
                List<Role> roleList = new ArrayList<>();
                for (Role role : roles) {
                    roleList.add(role);
                }
                String[] roleStr = new String[roleList.size()];
                for (int i = 0; i < roleList.size(); i++) {
                    roleStr[i] = roleList.get(i).getKeyword();
                }
                //将筛选出来的url路径所具有的角色返回回去
                return SecurityConfig.createList(roleStr);
            }
        }
        //如果没有匹配，返回一个默认的
        return SecurityConfig.createList("ROLE_def");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
